package com.bckj.fastboot.iot.biz.service.impl;

import com.bckj.fastboot.iot.biz.repository.IotDeviceRepository;
import com.bckj.fastboot.iot.common.constant.IotDeviceConstants;
import com.bckj.fastboot.iot.common.dto.ctx.IotDeviceContext;
import com.bckj.fastboot.iot.common.entity.IotDevice;
import com.bckj.fastboot.iot.common.enums.IotDeviceEvent;
import com.bckj.fastboot.iot.common.enums.IotDeviceState;
import com.bckj.fastboot.iot.common.service.IotDeviceScheduledService;
import com.bckj.fastboot.iot.biz.service.IotDeviceFireEventService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * IotDeviceHeartbeatCheckServiceImpl
 *
 * @author wfc
 **/
@Service
@RequiredArgsConstructor
public class IotDeviceScheduledServiceImpl implements IotDeviceScheduledService {

    private final IotDeviceRepository iotDeviceRepository;
    private final IotDeviceFireEventService iotDeviceFireEventService;

    @Override
    public void checkHeartbeat() {
        LocalDateTime dt = LocalDateTime.now().plusMinutes(30);
        List<IotDevice> list = iotDeviceRepository.lambdaQuery()
                .eq(IotDevice::getStatus, IotDeviceConstants.STATUS_ONLINE)
                .lt(IotDevice::getLastLiveTime, dt)
                .list();
        for (IotDevice iotDevice : list) {
            var ctx = IotDeviceContext.create()
                    .setId(iotDevice.getId())
                    .setDevCode(iotDevice.getDevCode());
            iotDeviceFireEventService.fire(IotDeviceState.ONLINE, IotDeviceEvent.DISCONNECT, ctx);
        }
    }
}
